package com.heima.big_event03.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.big_event03.entity.Article;
import com.heima.big_event03.entity.PageBean;
import com.heima.big_event03.mapper.ArticleDao;
import com.heima.big_event03.service.ArticleService;
import com.heima.big_event03.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;
//import org.springframework.data.domain.Page;
//import org.springframework.data.domain.PageImpl;
//import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * (Article)表服务实现类
 *
 * @author makejava
 * @since 2025-03-04 20:44:01
 */
@Service("articleService")
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleDao articleDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Article queryById(String id) {
        return this.articleDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param article 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
//    @Override
//    public Page<Article> queryByPage(Article article, PageRequest pageRequest) {
//        long total = this.articleDao.count(article);
//        return new PageImpl<>(this.articleDao.queryAllByLimit(article, pageRequest), pageRequest, total);
//    }

    /**
     * 新增数据
     *
     * @param a 实例对象
     * @return 实例对象
     */
    @Override
    public void insert(Article a) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String id = (String) claims.get("id");
        a.setCreateUser(id);
        a.setCreateTime(LocalDateTime.now());
        a.setUpdateTime(LocalDateTime.now());
        this.articleDao.insert(a);
    }

    /**
     * 修改数据
     *
     * @param a 实例对象
     * @return 实例对象
     */
    @Override
    public void update(Article a) {
        a.setUpdateTime(LocalDateTime.now());
        this.articleDao.update(a);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public void deleteById(String id) {
        this.articleDao.deleteById(id);
    }

    /**
     * 文章列表
     * @return
     */
    @Override
    public PageBean<Article> list(Integer pageNum,
                                  Integer pageSize,
                                  Integer categoryId,
                                  String state) {
        PageBean<Article> pb = new PageBean<>();
        PageHelper.startPage(pageNum,pageSize);
        Map<String, Object> claims = ThreadLocalUtil.get();
        String id = (String) claims.get("id");
        List<Article> as = articleDao.list(id,categoryId,state);
        Page<Article> p = (Page<Article>) as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }
}
